﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Web;

namespace Common
{
    public static class ErrorHandler
    {
        public static void LogOnly(string errMessage)
        {
            WriteLog(errMessage);
        }

        public static void Log(ERROR_MODEL errorModel)
        {
            var errMessage = BuildErrorString(errorModel);
            WriteLog(errMessage);
        }

        public static void LogAndThrow(string errMessage)
        {
            WriteLog(errMessage);
            throw new Exception(errMessage);
        }

        private static void WriteLog(string errMessage)
        {
            var logFile = HttpContext.Current.Server.MapPath(Variables.LogPathFile);
            if (!File.Exists(logFile))
            {
                using (var f = new FileStream(logFile, FileMode.Create))
                {
                    StreamWriter writer = new StreamWriter(f);
                    writer.WriteLine(errMessage);
                    writer.Flush();
                    writer.Close();
                    f.Close();
                }
            }
            else
            {
                StreamWriter writer = new StreamWriter(logFile, true);
                writer.WriteLine(errMessage);
                writer.Flush();
                writer.Close();
            }

            return;
        }

        private static string BuildErrorString(ERROR_MODEL errorModel)
        {
            var result = string.Format("DateTime: {0} - Object: {1} - Class: {2} - Function: {3} - Error: {4}",
                errorModel.ErrorDateTime.ToString("dd/MMM/yyyy hh:MM:ss"), errorModel.ObjectName, errorModel.ClassName,
                errorModel.FunctionName, errorModel.ErrorMessage);

            return result;
        }
    }
}
